import { ApiResponse, PaginationParams } from '@/types';

// API基础URL
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api';

// 通用请求函数
export async function fetchApi<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<ApiResponse<T>> {
  const response = await fetch(`${BASE_URL}${endpoint}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  if (!response.ok) {
    throw new Error(`API请求失败: ${response.statusText}`);
  }

  return response.json();
}

// GET请求
export async function get<T>(endpoint: string): Promise<ApiResponse<T>> {
  return fetchApi<T>(endpoint, {
    method: 'GET',
  });
}

// POST请求
export async function post<T>(
  endpoint: string,
  data: any
): Promise<ApiResponse<T>> {
  return fetchApi<T>(endpoint, {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

// 带分页的GET请求
export async function getPaginated<T>(
  endpoint: string,
  params: PaginationParams
): Promise<ApiResponse<T>> {
  const queryParams = new URLSearchParams({
    page: params.page.toString(),
    pageSize: params.pageSize.toString(),
  });

  return fetchApi<T>(`${endpoint}?${queryParams}`, {
    method: 'GET',
  });
}

// 错误处理函数
export function handleApiError(error: any): string {
  if (error instanceof Error) {
    return error.message;
  }
  return '发生未知错误';
} 